<?php
/**
 * Simple Light PHP Framework
 *
 * @copyright Marc PEPIN 2012
 * @author Marc PEPIN
 *
 */

defined('SLP_ROOT') or die("You've not access to this page");

/** 
* Simple Light Php Framework Path Class
* @package		Slp
* @author    	Marc PEPIN
*/ 

class Slp_Path {
	
	/**
	* Constructor
	*/
	
	public function __construct() {
		$this->renderCurrentPath();	
	}
	
	/**
	* Get Controller param
	* @return object
 	*/
	
	private function controllerParam() {
		$config = Slp::getInstance()->loaded->Slp_Config;
		$path = isset($_GET['q'])  ? explode('/', $_GET['q']) : array();
		$controller = new stdClass;
		$controller->class = isset($path[0]) && !empty($path[0]) ? $path[0] : $config->get('defaultController');
		$controller->method = isset($path[1]) && !empty($path[1]) ? $path[1] : 'index';
		$controller->args = isset($path[2]) ? array() :  NULL;
		for ($i = 2; $i < count($path); $i++)
			array_push($controller->args, $path[$i]);
		return $controller;
}

	/**
	* Load Current Path Controller
	* @return Slp_Controller
	*/
	
	private function loadCurrentController() {
		$c = $this->controllerParam();
		
		if (!is_file(SLP_ROOT.'/application/controllers/'.$c->class.'.php'))
			return Slp::getInstance()->loaded->Slp_Common->error404();	
		else
		{
			
			include(SLP_ROOT.'/application/controllers/'.$c->class.'.php');
			try {
					$reflection = new ReflectionMethod($c->class, $c->method);
					$requireArgsCount = $reflection->getNumberOfParameters();
					
					if ($requireArgsCount != count($c->args))
						return Slp::getInstance()->loaded->Slp_Common->error404();
				}
				catch (ReflectionException $e) {
					return Slp::getInstance()->loaded->Slp_Config->error404();	
				}
		}
		
		$controller = new $c->class();
		if (count($c->args) == 0)
			return $controller->{$c->method}(); 
		return $controller->{$c->method}($c->args); 
	}

	/**
	* Render Controller at current path
	*/
	
	function renderCurrentPath() {
		$content = $this->loadCurrentController();
		$tpl = Slp::getInstance()->loadClass("Slp_Template", array("page"));
		$tpl->assign(array('content' => $content));
		echo $tpl->render();
		
	}

}

?>